'''
操作mysql的工具类
功能:
1. 获取连接
2. CURD(增删改查)独立公用的方法
'''
import 分类字段
import pymysql
class SqlDb(object):
    #构造方法,初始化对象信息
    def __init__(self, host,db,user,password):
        self.host =host
        self.db = db
        self.user= user
        self.password = password
        self.charset='utf8'
    #获得连接
    def get_conn(self):
        conn = pymysql.connect(host=self.host,
                               port=3306,db=self.db,
                               user=self.user,
                               password=self.password)
        return conn
    def my_fetchall(self,conn,sql,canshu):
        cursor = conn.cursor()
        if canshu=="":
            cursor.execute(sql)
        else:
            cursor.execute(sql,canshu)
        rows = cursor.fetchall()
        cursor.close()
        conn.close()
        return rows
    def execute_sql(self,conn,sql,canshu):
        try:
            cursor = conn.cursor()
            num = cursor.execute(sql,canshu)
            pk = cursor.lastrowid
            print(pk)
            conn.commit()

            cursor.close()
            conn.close()
            return pk
        except Exception as e:
            print(e)
            conn.rollback()

            return 0
      
if __name__ == '__main__':
    s = SqlDb('39.96.186.239','shangpin','mrzhao','123456')

    a = 分类字段.a
    sql = "insert into home_category (`name`,is_root,parent_id,size_id) VALUES(%s,%s,%s,%s);"

    for key1,value1 in a.items():
        print('这是key1' + str(key1))

        conn = s.get_conn()
        canshu = [key1,1,None,None]
        w1 = s.execute_sql(conn, sql, canshu)
        print(w1)
        for key2,value2 in value1.items():
            print('这是key2' + str(key2))

            conn = s.get_conn()
            canshu = [key2, 0, w1, None]
            w2 = s.execute_sql(conn, sql, canshu)
            print(w2)
            for key3,value3 in value2.items():
                print('这是key3' + str(key3))

                conn = s.get_conn()
                canshu = [key3, 0, w2, None]
                w3 = s.execute_sql(conn, sql, canshu)
                print(w3)
                for d in value3:
                    print('这是d'+str(d))
                    conn = s.get_conn()
                    canshu = [d, 0, w3, None]
                    s.execute_sql(conn, sql, canshu)

